package com.borqs.samples;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class sampleActivity extends Activity implements OnItemClickListener {
    private final String TAG = "sampleActivity";

    private ListView mList = null;
    private Cursor mCursor = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sample_layout);
        int sessionID = getIntent().getExtras().getInt("1");
        findView();

        Cursor c = querySamples(DBProvider.SamplesTable.CONTENT_URI,
                DBProvider.SamplesTable.SESSION_ID, sessionID);
        setAdapter(c);
        mCursor = c;
    }

    private void findView() {
        mList = (ListView) findViewById(R.id.sample_list);
        mList.setOnItemClickListener(this);
    }

    private Cursor querySamples(Uri uri, String whereRow, int where) {
        Cursor c = null;
        if (null != whereRow) {
            c = getContentResolver().query(uri, null, whereRow + "=?",
                    new String[] { where + "" }, "_id ASC");
        } else {
            c = getContentResolver().query(uri, null, null, null, "_id ASC");
        }

        if (c != null && c.moveToFirst()) {
            // String leader = c
            // .getString(c
            // .getColumnIndexOrThrow(DBProvider.SessionsTable.START_AVERAGE));
            // Log.i(TAG, "leader.name=" + leader);
            return c;
        } else {
            Log.i(TAG, "query failure!");
        }
        return null;
    }

    private void setAdapter(Cursor c) {
        String[] from = new String[] { DBProvider.SamplesTable.SESSION_ID,
                DBProvider.SamplesTable.TIME };
        int[] to = new int[] { R.id.start_time, R.id.start_average_v };

        SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this,
                R.layout.sessions_list_item, c, from, to, 0);
        mList.setAdapter(simpleCursorAdapter);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        int _id = 0;
        mCursor.moveToFirst();
        mCursor.move(position);
        _id = mCursor.getInt(mCursor
                .getColumnIndex(DBProvider.SamplesTable._ID));
        Intent intent = new Intent(this, DataActivity.class);
        intent.putExtra("1", _id);
        startActivity(intent);
    }

}
